package cn.schoolwow.quickdao.module.database.dml.instance.flow.update.flow;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.domain.provider.DatabaseProvider;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.List;

public class SetUpdateInstanceStatementFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        Entity entity = (Entity) flowContext.checkData("entity");
        List<Property> setPropertyList = flowContext.checkData("setPropertyList", List.class);
        List<Property> wherePropertyList = flowContext.checkData("wherePropertyList", List.class);
        DatabaseProvider databaseProvider = quickDAOConfig.databaseContext.databaseProvider;

        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("update " + quickDAOConfig.databaseContext.databaseProvider.escape(entity.tableName) + " set ");
        for(Property property:setPropertyList){
            sqlBuilder.append(databaseProvider.escape(property.column) + " = " + (null == property.function ? "?" : property.function) + ",");
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
        sqlBuilder.append(" where ");
        for(Property property:wherePropertyList){
            sqlBuilder.append(databaseProvider.escape(property.column) + " = ? and ");
        }
        sqlBuilder.delete(sqlBuilder.length() - 5, sqlBuilder.length());

        flowContext.putTemporaryData("sql", sqlBuilder.toString());
    }

    @Override
    public String name() {
        return "更新实例-设置SQL语句";
    }

}
